
const DATA_TABLES = (function(){
    const DEFAULT_FORM_DATA = {
        idvClassId: 1,
        year: new Date().getFullYear() - 1
    };
    const DATA_URL = 'fetchDataTableSummary';

    let page = (title)=>{
        const PAGE_SETTING = {
            '人数': 1,
            '人次': 2,
            '总费用': 3,
            '医保支付': 4,
            '居家时间': 5
        };
        return {
            typeId: PAGE_SETTING[title],
            title: title,
            dataUrl: DATA_URL,
            initFormData: DEFAULT_FORM_DATA
        }
    };

    return {
        1: {
            name: '机构统计表',
            pages: [page('人数'), page('人次'), page('总费用'), page('医保支付')]
        },
        2: {
            name: '居家统计表',
            pages: [page('人数'), page('人次'), page('居家时间'),page('总费用'), page('医保支付')]
        },
        3: {
            name: '评估统计表',
            pages: [page('人数'), page('人次'), page('总费用'), page('医保支付')]
        }
    }

})();

const INDIVIDUAL_CLASS = {1:'一类', 2: '二类', 3: '特殊', 4: '帮困'}; //人员类型

const MONTH_FIELD = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
const MONTH_TITLE = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
//月份表头
const COLUMN = (function () {
    let list = [];
    list.push({
        field: 'YYNAME', title: '机构名字', width: 200
    });
    for(let i in MONTH_FIELD){
        list.push({
            field: MONTH_FIELD[i],
            title: MONTH_TITLE[i],
            sort: true,
            width: 100
        })
    }
    list.push({
        field: 'total', title: '合计', width: 120
    });
    return list;
})();


$(function () {


    layui.use(['jquery', 'form', 'layer', 'table', 'laytpl', 'laydate', 'element'], function() {
        var $ = layui.jquery, form = layui.form, layer = layui.layer, table = layui.table,
            laytpl = layui.laytpl,laydate = layui.laydate, element = layui.element;

        //当前数据表ID
        const REPORT_ID = CURRENT_REPORT_ID;
        //数据表名字
        const DATA_TABLE_NAME = DATA_TABLES[REPORT_ID].name;

        const NOW_DATE = new Date();
        const NOW = [NOW_DATE.getFullYear(), NOW_DATE.getMonth(), NOW_DATE.getDate()].join('-');

        var TableContent = (function () {
            const html = $('#contentItemLayer')[0].innerHTML;
            //切换标志
            let switchFlag = {};
            let contents = {};

            /**
             * 添加选项卡
             * @param {{title:string, dataUrl:string, typeId:integer,initFormData:{}}} setting
             * @return {{init: function, id: number}}
             */
            let addTable = function (setting) {
                let initFormData = setting.initFormData;
                let dataUrl = setting.dataUrl;
                let title = setting.title;
                let typeId = setting.typeId;
                let pageId = Date.now();
                let dom = $(laytpl(html).render({id: pageId}));

                let hasInitTable = false;
                let tabIns;

                /**
                 * 行求和
                 * @param data
                 */
                let summaryRow = function(data){
                    if(!data){return;}
                    data.forEach((each)=>{
                        let sum = 0;
                        for(let key in each){
                            if(typeof each[key] == 'number'){
                                sum += each[key];
                            }
                        }
                        each.total = sum;

                    })

                };

                let updateTable = function(formData){
                    formData.reportId = REPORT_ID;
                    formData.typeId = typeId;
                    // console.log('formData', formData);
                    let tableTitle = [(formData.year || ''),  DATA_TABLE_NAME, title].join('-');

                    let complete = function () {
                        $('#formQuerySearch-' + pageId).removeAttr('disable');
                        window.resizeWindowHeight?window.resizeWindowHeight():'';
                    };
                    if(!hasInitTable){
                        hasInitTable = true;
                        //初始化表格
                        tabIns = table.render({
                            title: tableTitle,
                            elem: '#dataTable-' + pageId,
                            url: dataUrl,
                            method: "POST",
                            page: true, //开启分页
                            loading: true,
                            width: '100%',
                            toolbar: true,
                            defaultToolbar: ['filter', 'print', 'exports', {
                                title: '导出所有',
                                layEvent: 'export_all',
                                icon: 'layui-icon-template-1' //图标类名
                            }],
                            limit: 15,
                            page: {
                                layout:['prev', 'page', 'next', 'skip', 'count'],
                            },//开启分页
                            even: true, //隔行背景
                            size: 'sm',
                            cellMinWidth: 60,
                            cols: [COLUMN],
                            where: formData,
                            request: {
                                pageName: 'page',
                                limitName: 'size'
                            },
                            parseData: function(res){ //res 即为原始返回的数据
                                let count = res.data && res.data.count || 0;
                                if(count > 0){ this.where.count = count; } //记录最大记录数
                                summaryRow(res.data && res.data.data);
                                return {
                                    "code": res.code, //解析接口状态
                                    "msg": res.msg, //解析提示文本
                                    "count": count, //解析数据长度
                                    "data": res.data && res.data.data//解析数据列表
                                };
                            },
                            done: function () {
                                complete();
                            }

                        });
                    }else{
                        tabIns.config.where = {}; //清除请求参数
                        tabIns = table.reload('dataTable-' + pageId, {
                            title: tableTitle,
                            where: formData,
                            page: {
                                curr: 1 //重新从第 1 页开始
                            },
                            done: function () {
                                console.log('重载完成');
                                complete();
                            },
                            error: function (error, data) {
                                console.log('重载失败', error);
                                complete();
                            }
                        }); //只重载数据
                    }

                };

                element.tabAdd('table-content', {
                    title: title,
                    content: '',
                    id: pageId
                });
                //查找添加的div
                let content = (function () {
                    let title = $('#table-content>ul>li[lay-id=' + pageId + ']');
                    // console.log('title', title);
                    return $('#table-content>div.layui-tab-content').children().eq(title.index());
                })();
                //添加
                content.append(dom);

                //表单提交
                form.on('submit(formQuerySearch-' + pageId + ')', function(data){
                    let field = data.field;
                    // console.log('field', field);

                    //发送请求
                    updateTable(field);

                    //禁用当前按钮
                    $(data.elem).attr('disable', 'disable');
                    return false;
                });

                form.val('filter-form-' + pageId, initFormData);

                //日期
                // console.log(NOW);
                laydate.render({
                    elem: '#queryDate-' + pageId,
                    type: 'year',
                    value: initFormData.year,
                    format: 'yyyy',
                    isInitValue: true,
                    min: '2018-01-02',
                    max: NOW,
                    theme: 'grid'
                });

                form.render(null, 'filter-form-' + pageId);

                
                //数据导出
                let download = function(){
                    let formData = form.val('filter-form-' + pageId);
                    // console.log(formData);
                    formData.count = 1; //防止查询时重新计数
                    formData.reportId = REPORT_ID;
                    formData.typeId = typeId;

                    let loadingIndex = layer.load(2, {time: 10*1000}); //加载动画

                    layui.config({//配置并导入excel插件
                        base: '/js/layui_exts/'
                    }).use('excel', function() {
                        let excel = layui.excel;
                        $.ajax({
                            url: dataUrl,
                            method:'post',
                            data:formData,
                            success: (res) =>{
                                if(res.code != 0){
                                    layer.msg(res.msg, {icon: 2});
                                    return;
                                }

                                let data = res.data.data;
                                let fields = (function () {
                                    let cols = tabIns.config.cols[0]; //表格表头
                                    let fields = {};
                                    let title = {};
                                    for(let i in cols){
                                        fields[cols[i].title] = cols[i].field;
                                        title[cols[i].title] = cols[i].title;
                                    }
                                    return {title : title, fields: fields};

                                })();
                                // console.log('data', data);
                                // console.log('fields', fields);
                                summaryRow(data);
                                data = excel.filterExportData(data, fields.fields);
                                data.unshift(fields.title);
                                // console.log('data', data);
                                excel.exportExcel(
                                    data,
                                    [DATA_TABLE_NAME, title, INDIVIDUAL_CLASS[typeId] || '', formData.year || '', '.xlsx'].join('-'),
                                    'xlsx');
                            },
                            error: ()=> {
                                layer.msg(res.status || '未知的错误', {icon: 2});
                            },
                            complete: ()=>{
                                layer.close(loadingIndex);
                            }
                        });
                    });
                };

                //表格头部工具栏事件
                table.on('toolbar(dataTable-' + pageId + ')', function(obj){
                    switch(obj.event){
                        case 'export_all':
                            download();
                            break;
                    };
                });

                return {
                    id: pageId,
                    init: function () {
                        // console.log('init', initFormData);
                        updateTable(initFormData);
                    }
                }
            };

            //监听切换
            element.on('tab(table-content)', function(data){
                // console.log(this); //当前Tab标题所在的原始DOM元素
                // console.log(data.index); //得到当前Tab的所在下标
                // console.log(data.elem); //得到当前的Tab大容器
                let id = $(this).attr('lay-id');
                // console.log(id);
                if(!id){return;}


                if(! (id in switchFlag)){
                    let content = contents[id];
                    // console.log(content);
                    if(!content){return;}
                    switchFlag[id] = true;
                    content.init();
                }
            });
            //初始切换


            return {
                add:function (settings) {
                    //批量添加选项卡
                    let tabs = [];
                    for(let k in settings){
                        let tab = addTable(settings[k]);
                        tabs.push(tab);
                        contents[tab.id] = tab;
                    }


                }
            }
        })();


        //添加content
        TableContent.add(DATA_TABLES[REPORT_ID].pages);
        //初始显示第一个栏目
        let firstTabId = $('#table-content>ul.layui-tab-title>li:first-child').attr('lay-id');
        if(firstTabId){
            element.tabChange('table-content', firstTabId);
        }


    })
});